﻿#include "threadpool.h"
// 创建线程池
struct threadpool* create_threadpool(int threads, int queue_length, void* (*consumer)(void*))
{
	struct threadpool* p = malloc(sizeof(struct threadpool));//!!!

	p->tids = malloc(sizeof(pthread_t) * threads);
	int ret = 0;
	sem_init(&p->semw, 0, queue_length);
	sem_init(&p->semr, 0, 0);
	pthread_mutex_init(&p->mutex, NULL);

	for (int i = 0; i < threads; i++)//创建消费者线程
	{
		ret = pthread_create(&p->tids[i], NULL, consumer, p);
		if (ret != 0)
		{
			perror("pthread_create");
		}
	}

	return p;	
}

//销毁线程池
void destroy_threadpool(struct threadpool* p, int threads)
{
	for (int i = 0; i < threads; i++)
	{
		pthread_join(p->tids[i], NULL);
	}

	sem_destroy(&p->semw);
	sem_destroy(&p->semr);
	pthread_mutex_destroy(&p->mutex);
	free(p->tids);		
	free(p);	

	
}
